// Copyright 2017 Baidu Inc. All Rights Reserved.
// Author: Duan Lian (duanlian01@baidu.com)
//
// Description: OTA URL

#include "baidu_iot_ota_url.h"
#include <stdlib.h>
#include <string.h>
#include "duer_log.h"
#include "heap_monitor.h"
#include "baidu_iot_ota_log.h"

namespace duer {

URL::URL(const char* url) :
      _valid(false),
      _scheme(NULL), _host(NULL), _port(NULL), _path(NULL) {
    _valid = parse(url);
}

URL::~URL() {
    if (_scheme) {
        FREE(_scheme);
        _scheme = NULL;
    }

    if (_host) {
        FREE(_host);
        _host = NULL;
    }

    if (_path) {
        FREE(_path);
        _path = NULL;
    }

    if (_url) {
        FREE(_url);
        _url = NULL;
    }
}

bool URL::parse(const char* url) {
    OTA_FUNC_ENTER();

    if (!url) {
        DUER_LOGE("Argument invalid");

        return false;
    }

    bool valid = false;
    int url_len = strlen(url) + 1;
    _url = (char*)MALLOC(url_len, OTA);

    if (_url) {
        memmove(_url, url, url_len);
    }

    do {
        char* p = strchr((char*)url, ':');

        if (!p || p <= url) {
            break;
        }

        _scheme = (char*)MALLOC(p - url + 1, OTA);
        memset(_scheme, 0, p - url + 1);
        memmove(_scheme, url, p - url);

        if (strncmp(_scheme, "http", 4) && strncmp(_scheme, "coap", 4)) {
            FREE(_scheme);
            _scheme = NULL;
            break;
        }

        DUER_LOGD("_scheme:%s", _scheme);
        url = p + 3;
        p = strchr((char*)url, ':');

        if (p) {
            _host = (char*)MALLOC(p - url + 1, OTA);
            memset(_host, 0, p - url + 1);
            memmove(_host, url, p - url);
            url = p + 1;
            p = strchr((char*)url, '/');

            if (p) {
                char* port = (char*)MALLOC(p - url + 1, OTA);
                memset(port, 0, p - url + 1);
                memmove(port, url, p - url);
                _port = atoi(port);
            }
        } else {
            p = strchr((char*)url, '/');

            if (p) {
                _host = (char*)MALLOC(p - url + 1, OTA);
                memset(_host, 0, p - url + 1);
                memmove(_host, url, p - url);
            }

            if (0 == strncmp(_scheme, "http", 4)) {
                _port = 80;
            } else if (0 == strcmp(_scheme, "coaps")) {
                _port = 5684;
            }
        }

        DUER_LOGD("_host:%s\n_port:%d\n", _host, (int)_port);
        url = p + 1;
        int url_len = strlen(url) + 1;
        _path = (char*)MALLOC(url_len, OTA);
        memmove(_path, url, url_len);
        DUER_LOGD("_path:%s", _path);
        valid = true;
    } while (0);

    OTA_FUNC_LEAVE();

    return valid;
}

} // namespace duer
